package thread;

//模拟实现阻塞队列
class MyBlockingQueue{

    private Object locker = new Object();
    private String[] items = new String[1000];

    private volatile int head;

    private volatile int tail;

    private volatile int size;

    //入队列
    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while (size >= items.length) {
                // return;
                //队列满了,不可以再入队
                locker.wait();
            }
            items[tail] = elem;
            tail++;
            if (tail >= items.length) {
                tail = 0;
            }
            size++;
            locker.notify();
        }
    }
    //出队列
    public String take() throws InterruptedException {
        synchronized (locker) {
            while (size == 0) {
                //return null;
                //队列空了,不可以再出队
                locker.wait();
            }
            String elem = items[head];
            head++;
            if (head >= items.length) {
                head = 0;
            }
            size--;
            locker.notify();
            return elem;

        }
    }

}

public class Demo15 {

    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();

        //生产元素
        Thread t1 = new Thread(() -> {
            String count = "0";
            while (true) {
                System.out.println("开始生产元素：" + count);
                try {
                    queue.put(count);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });

        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    String n = queue.take();
                    System.out.println("开始消费元素： " + n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        t1.start();
        t2.start();
    }

}
